package com.demo.test.util.xml;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class XmlParserUtil {

    private final XmlMapper xmlMapper;

    public XmlParserUtil() {
        this.xmlMapper = new XmlMapper();
    }

    /**
     * 将XML字符串解析为Map对象
     *
     * @param xml XML字符串
     * @return 解析后的Map对象
     * @throws Exception 解析异常
     */
    public Map<String, Object> parseXmlToMap(String xml) throws Exception {
        return xmlMapper.readValue(xml, Map.class);
    }

    /**
     * 根据路径获取XML节点值
     *
     * @param xml XML字符串
     * @param path 节点路径，使用"."分隔（例如: "root.child"）
     * @return 节点值
     * @throws Exception 解析异常
     */
    public Object getXmlNodeValue(String xml, String path) throws Exception {
        Map<String, Object> map = parseXmlToMap(xml);
        return getNodeValueByPath(map, path);
    }

    /**
     * 根据路径获取Map中的值
     *
     * @param map 数据Map
     * @param path 节点路径，使用"."分隔
     * @return 节点值
     */
    @SuppressWarnings("unchecked")
    private Object getNodeValueByPath(Map<String, Object> map, String path) {
        String[] paths = path.split("\\.");
        Object value = map;
        
        for (String p : paths) {
            if (value instanceof Map) {
                value = ((Map<String, Object>) value).get(p);
            } else {
                return null;
            }
        }
        
        return value;
    }

    /**
     * 将对象转换为XML字符串
     *
     * @param object 对象
     * @return XML字符串
     * @throws Exception 转换异常
     */
    public String objectToXml(Object object) throws Exception {
        return xmlMapper.writeValueAsString(object);
    }
}